
# 反向迭代，反方向迭代一个序列
# 使用内置的reversed()函数
def demo_1():
    a = [1,2,3,4]
    for x in reversed(a):
        print(x)

# 反向迭代文本列表
def demo_2():
    f = open("../temp/pome.txt")
    for line in reversed(list(f)):
        print(line, end='')

# 可以通过在自定义类上实现__reversed__()方法来实现反向迭代
class Countdown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1

    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1

def demo_3():
    # 反向迭代
    for rr in reversed(Countdown(5)):
        print(rr)
    # 正向迭代
    for rr in Countdown(5):
        print(rr)

if __name__ == '__main__':
    # demo_1()
    # demo_2()
    demo_3()